package main

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"os"
	"youbei/task"
)

/*
	生成秘钥函数
*/
func GenRsaKey(bits int) (error, map[string]string) {

	privateKey, err := rsa.GenerateKey(rand.Reader, bits)
	if err != nil {
		return err, nil
	}
	derStream := x509.MarshalPKCS1PrivateKey(privateKey)
	block := &pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: derStream,
	}
	uuidkey := task.Generate_uuid()
	keyfilemap := make(map[string]string)
	keyfilemap["pri"] = uuidkey + "_pri.pem"
	keyfilemap["pub"] = uuidkey + "_pub.pem"
	file, err := os.Create(keyfilemap["pri"])
	if err != nil {
		return err, nil
	}
	err = pem.Encode(file, block)
	if err != nil {
		return err, nil
	}

	publicKey := &privateKey.PublicKey
	derPkix, err := x509.MarshalPKIXPublicKey(publicKey)
	if err != nil {
		return err, nil
	}
	block = &pem.Block{
		Type:  "PUBLIC KEY",
		Bytes: derPkix,
	}

	file, err = os.Create(keyfilemap["pub"])
	if err != nil {
		return err, nil
	}
	err = pem.Encode(file, block)
	if err != nil {
		return err, nil
	}
	return nil, keyfilemap
}
